function toYuan(val) {
  return (val / 100.0).toFixed(2)
}

function parseFormData(val) {
  Object.keys(val).forEach(item => {
    if (typeof val[item] === 'undefined' || val[item] === null || val[item] === '') {
      delete val[item];
    }
  })
  return val;
}

function formatSize(val) {
  if (val === 0) {
    return "0 B"
  }
  const k = 1024;
  const sizes = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]
  const i = Math.floor(Math.log(val) / Math.log(k));
  return `${`${(val / (k ** i)).toPrecision(3)} ${sizes[i]}`}`;
}

function filterByDict(val, dict, allName) {
  if (dict) {
    // 如果val为多个
    if (typeof (val) === 'string' && val.split(",").length > 1) {
      const valList = []
      val.split(",").forEach(v => {
        const item = dict.find(item => item.value.toString() === v)
        if (item !== undefined) {
          valList.push(item.label)
        }
      })
      if (val.split(",").length === Object.keys(dict).length && allName) {
        return allName
      }
      return valList.join("、")

    }
    const item = dict.find(item => item.value === val)
    if (item !== undefined) {
      return item.label;
    }
  }
  return ""
}


function filterByTree(val, tree, children = "children", id = "id", label = "label") {
  let text = '';
  const convert = (arr) => {
    arr.filter((item) => {
      if (item[id] === val) {
        text = item[label]
      } else if (item[children]) {
        return convert(item[children])
      }
      return false
    })
  }
  convert(tree)
  return text
}

function filterParentsByTree(val, tree, children = "children", id = "id", label = "label") {
  const stock = [];
  let going = true;
  function recursion(tree, val, id, children) {
    tree.forEach((item) => {
      if (!going) return;
      stock.push(item[label]);
      if (item[id] === val) {
        going = false;
      } else if (item[children]) {
        recursion(item[children], val, id, children);
      } else {
        stock.pop();
      }
    });
    if (going)  stock.pop();
  }
  recursion(tree, val, id, children);
  return stock.join(" / ");
}


export default {toYuan, parseFormData, formatSize, filterByDict, filterByTree, filterParentsByTree}
